package cn.sdormitory.basedata.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.sdormitory.basedata.dao.BCourseDao;
import cn.sdormitory.basedata.entity.BClass;
import cn.sdormitory.basedata.entity.BCourse;
import cn.sdormitory.basedata.service.BCourseService;
import cn.sdormitory.basedata.vo.CourseQueryVo;
import cn.sdormitory.common.constant.CommonConstant;
import cn.sdormitory.common.utils.SysUserUtils;
import cn.sdormitory.school.entity.SchoolPatrolHandle;
import cn.sdormitory.sys.dao.SysDictDetailDao;
import cn.sdormitory.sys.entity.SysDictDetail;
import cn.sdormitory.sys.entity.SysUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class BCourseServiceImpl extends ServiceImpl<BCourseDao, BCourse> implements BCourseService {

    @Autowired
    BCourseDao bCourseDao;

    @Autowired
    SysDictDetailDao sysDictDetailDao;

    @Override
    public IPage<BCourse> findPageList(CourseQueryVo queryVo) {
        int count = bCourseDao.findPageListCount(queryVo);
        int startNum = (queryVo.getPageNum() - 1) * queryVo.getPageSize();
        // 查出课程列表
        List<BCourse> list = bCourseDao.findPageList(startNum,queryVo.getPageSize(),queryVo);
        // 查询出章节列表
        List<BCourse> sectionList = bCourseDao.findSectionList(queryVo);
        Map<String, List<BCourse>> collect = sectionList.stream().collect(Collectors.groupingBy(BCourse::getCourseName));
        for (BCourse bCourse : list) {
            List<BCourse> courseList = collect.get(bCourse.getCourseName());
            if (CollectionUtil.isEmpty(courseList)) {
                continue;
            }
            for (BCourse course : courseList) {
                course.setCourseNo(null);
            }
            bCourse.setChildren(courseList);
        }
        
        IPage<BCourse> page = new Page<>();
        page.setTotal(count);
        page.setRecords(list);
        return page;
    }

    @Override
    @Transactional
    public Integer createOrUpdateCourse(BCourse bCourse) {
        int flag = 0;
        // 添加 添加课程 也添加章节
        if(bCourse.getId() == null){
            List<BCourse> courseList = new ArrayList<>();
            bCourse.setCreateBy(SysUserUtils.getSysUser().getUsername());
            bCourse.setCreateTime(new Date());
            courseList.add(bCourse);
            for (BCourse section : bCourse.getSectionList()) {
                BCourse course = new BCourse();
                course.setSectionNo(section.getSectionNo());
                course.setCourseSection(section.getCourseSection());
                course.setCreateBy(SysUserUtils.getSysUser().getUsername());
                course.setCreateTime(new Date());
                course.setCourseName(bCourse.getCourseName());
                course.setCourseTerm(bCourse.getCourseTerm());
                course.setStatus(bCourse.getStatus());
                courseList.add(course);
            }
            saveBatch(courseList);
            return courseList.size();
        }
        // 修改 需要更新课程信息，也要更新章节信息
        flag = bCourseDao.updateById(bCourse);
        List<BCourse> children = bCourse.getSectionList();
        if (CollectionUtil.isEmpty(children)) {
            return flag;
        }
        // 先删除之前的章节
        LambdaQueryWrapper<BCourse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BCourse::getCourseName, children.get(0).getCourseName());
        List<BCourse> courseList = bCourseDao.selectList(queryWrapper);
        List<Long> ids = courseList.stream().map(BCourse::getId).collect(Collectors.toList());
        ids.remove(bCourse.getId());
        bCourseDao.deleteBatchIds(ids);
        String username = SysUserUtils.getSysUser().getUsername();
        List<BCourse> updateCourse = new ArrayList<>();
        for (BCourse course : children) {
            course.setCourseName(bCourse.getCourseName());
            course.setCourseTerm(bCourse.getCourseTerm());
            course.setStatus(bCourse.getStatus());
            if (Objects.isNull(course.getId())) {
                course.setCreateBy(username);
                course.setCreateTime(new Date());
            } else {
                course.setModifyBy(username);
                course.setModifyTime(new Date());
            }
            updateCourse.add(course);
        }
        saveOrUpdateBatch(updateCourse);
        return flag;
    }

    @Override
    public List<SysDictDetail> findAllCourseTerm() {
        QueryWrapper<SysDictDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_type","course_term");
        List<SysDictDetail> sysDictDetails = sysDictDetailDao.selectList(wrapper);
        return sysDictDetails;
    }

    @Override
    public List<BCourse> findAllCourse() {
        // 查找出所有的课程
        List<BCourse> courseList = list(new LambdaQueryWrapper<BCourse>().eq(BCourse::getStatus, CommonConstant.VALID_STATUS).isNull(BCourse::getCourseSection));
        List<String> courseNames = courseList.stream().map(BCourse::getCourseName).collect(Collectors.toList());
        
        // 查找出所有的章节
        List<BCourse> sectionList = list(new LambdaQueryWrapper<BCourse>().isNotNull(BCourse::getCourseSection).in(BCourse::getCourseName, courseNames));
    
        Map<String, List<BCourse>> collect = sectionList.stream().collect(Collectors.groupingBy(BCourse::getCourseName));
        for (BCourse bCourse : courseList) {
            List<BCourse> courses = collect.get(bCourse.getCourseName());
            if (CollectionUtil.isEmpty(courses)) {
                continue;
            }
            bCourse.setSectionList(courses);
        }
        return courseList;
    }
    
    @Override
    public int deleteByIds(Long id) {
        return bCourseDao.deleteById(id);
    }
}
